﻿using System.Diagnostics;
using MicroBlog.Infrastructure;
using MicroBlog.Models;
using MicroBlog.Services;
using MicroBlog.ViewModels;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace MicroBlog.Controllers
{
    public class HomeController : Controller
    {
        private readonly AppSettings _appSettings;
        private readonly IBlogManager _blogManager;
        private readonly IWebHostEnvironment _env;

        public HomeController(IOptions<AppSettings> options, IBlogManager blogManager, IWebHostEnvironment hostingEnvironment)
        {
            _appSettings = options.Value;
            _blogManager = blogManager;
            _env = hostingEnvironment;
        }
        public async Task<IActionResult> Index()
        {
            var model = await GetBlogsByKey(string.Empty);
            return View(model);
        }

        public async Task<IActionResult> Details(int id)
        {
            var model = await _blogManager.FindAsync(id);
            return View(model);
        }
        public async Task<IActionResult> Page(int id)
        {
            var model = await GetBlogsByKey(string.Empty, id);
            return View("Index", model);
        }

        public async Task<IActionResult> Tags()
        {
            var model = await _blogManager.GetTagsAsync();
            return View(model);
        }
        public async Task<IActionResult> SearchByKey(string key, int page = 1)
        {
            var model = await GetBlogsByKey(key, page);
            return View("Index", model);
        }
        public async Task<IActionResult> SearchByTag(string tag, int page = 1)
        {
            var model = await GetBlogsByTag(tag, page);
            return View("Index", model);
        }

        private async Task<IPagedList<Blog>> GetBlogsByKey(string key, int pageIndex = 1, int pageSize = 5)
        {
            var filterExpression = ExpressionExtensions.True<Blog>();
            if (!string.IsNullOrEmpty(key))
            {
                filterExpression = filterExpression.And(p => p.Title.Contains(key));
            }
            return await _blogManager.SearchAsync(filterExpression, pageIndex, pageSize);
        }
        private async Task<IPagedList<Blog>> GetBlogsByTag(string tag, int pageIndex = 1, int pageSize = 5)
        {
            return await _blogManager.SearchByTagAsync(tag, pageIndex, pageSize);
        }
        public IActionResult AccessDenied()
        {
            return View("~/Views/Shared/AccessDenied.cshtml");
        }
        public IActionResult Update()
        {
            return View();
        }
        public IActionResult Archives()
        {
            return View();
        }
        /// <summary>
        /// 前台统一错误处理页
        /// </summary>
        /// <param name="statusCode">状态代码</param>
        /// <returns></returns>
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error(int statusCode = 400)
        {
            IExceptionHandlerFeature exf = HttpContext.Features.Get<IExceptionHandlerFeature>();
            Exception ex = exf?.Error;

            return View(new ErrorViewModel
            {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier,
                StatusCode = statusCode,
                Description = _env.IsDevelopment() ? ex?.Message : "哎呦，出错了..."
            });
        }
        public IActionResult Exception()
        {
            throw new Exception("异常测试");
        }
    }
}
